package user

import (
	"context"

	"github.com/zeromicro/go-zero/core/logc"

	"gitee.com/liuxuezhan/ar-platform/admin-api/internal/svc"
	"gitee.com/liuxuezhan/ar-platform/admin-api/internal/types"

	"gitee.com/liuxuezhan/ar-platform/rpc-client/userServiceClient/userrpc"
	"github.com/zeromicro/go-zero/core/logx"
)

type UserLoginLogsListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 用户登录日志-列表
func NewUserLoginLogsListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserLoginLogsListLogic {
	return &UserLoginLogsListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserLoginLogsListLogic) UserLoginLogsList(req *types.UserLoginLogsListRequest) (resp *types.UserLoginLogsListResponse, err error) {
	rpcResp, err := l.svcCtx.UserServiceRPC.UserLoginLogList(l.ctx, &userrpc.UserLoginLogsRequest{
		Page:      req.Page,
		PageSize:  req.PageSize,
		UserId:    req.UserId,
		StartTime: req.StartTime,
		EndTime:   req.EndTime,
		Ip:        req.Ip,
	})
	if err != nil {
		logc.Error(l.ctx, "UserLoginLogsListLogic UserLoginLogList rpc error: %v", err)
		return &types.UserLoginLogsListResponse{
			LoginLogs:  []*types.UserLoginLogsListItem{},
			Pagination: &types.Pagination{},
		}, nil
	}
	resp = &types.UserLoginLogsListResponse{}
	userLoginLogsList := make([]*types.UserLoginLogsListItem, len(rpcResp.Data))
	pagination := &types.Pagination{
		Page:     rpcResp.Pagination.Page,
		PageSize: rpcResp.Pagination.PageSize,
		Total:    rpcResp.Pagination.Total,
	}
	for i, v := range rpcResp.Data {
		userLoginLogsList[i] = &types.UserLoginLogsListItem{
			Id:        v.Id,
			UserId:    v.UserId,
			Ip:        v.Ip,
			LoginTime: v.LoginTime,
			Device:    v.LoginDevice,
		}
	}
	resp.LoginLogs = userLoginLogsList
	resp.Pagination = pagination
	return
}
